<script setup lang="ts">
defineOptions({
  name: "deviceStatisticsTasks"
});
import { ref, onMounted, nextTick } from "vue";
import dayjs from "dayjs";
import { ArrowRightBold } from "@px-ui/icons-vue";
import modelBox from "@/views/common/components/modelBox/index.vue";
import deviceStatisticsTasksItem from "./deviceStatisticsTasksItem.vue";
import { getToken } from "@/utils/auth";
import echartsChart from "@/views/common/components/echartsChart/index.vue";
import { queryChildByTypeCodeAndItemValue } from "@/api/common";
import { queryTaskCount } from "@/api/modules/operation";
import { useRouter } from "vue-router";
const router = useRouter();

interface Props {
  height?: number;
  arrow?: boolean;
  dark?: boolean;
  title?: string;
  classCode?: string;
}

const props = withDefaults(defineProps<Props>(), {
  height: 234,
  arrow: false,
  dark: false,
  title: "今日任务",
  classCode: "GAS"
});

const deviceStatisticsTasksClass = ref<string>(`deviceStatisticsTasks_${Math.random().toString(36).slice(2, 10)}`);
const loadingInstance = ref<any>(null);
const categroyList = ref<any>([]);

const fourSubjectTaskViewPathMap = {
  GAS: "/gas/operation/taskView",
  MACHINE: "/machine/operation/taskOverView",
  ELECTRICTITY: "/electricity/operation/taskView",
  WATER: "/water/taskView"
};
const accessToken = getToken().accessToken || "";
const facCode = localStorage.getItem("facCode");
const tempList = ref<any[]>([
  {
    icon: "inspectionBg",
    label: "巡检任务",
    path: "/all/equip/inspect/task",
    query_done: { taskStatusList: "2-3-4-5" },
    query: { className: props.classCode, taskStatusList: "" }
  },
  {
    icon: "maintenanceBg",
    label: "保养任务",
    path: "/all/equip/epm/task/list",
    query_done: {
      fullpath: `/pmJob/list?ssoToken=${accessToken}&isHiddenMenu=true&className=${props.classCode}&jobStatus=["ONGOING","PAUSED"]&facCode=${facCode}`
    },
    query: { fullpath: `/pmJob/list?ssoToken=${accessToken}&isHiddenMenu=true&className=${props.classCode}&jobStatus=[]&facCode=${facCode}` }
  },
  {
    icon: "maintenanceBg1",
    label: "维修任务",
    path: "/all/equip/maintain/task",
    query_done: { status: "1-2-3-4-5-6" },
    query: { className: props.classCode, type: "list", status: "" }
  },
  {
    icon: "abnormalInspectionBg",
    label: "异常点检任务",
    path: "/all/equip/maintain/exception/task",
    query_done: { taskStatus: "1-2" },
    query: { className: props.classCode, taskStatus: "" }
  },
  {
    icon: "missingBg",
    label: "缺失任务",
    path: "/all/safeManage/defect",
    query_done: { status: "UNRESPONSE-UNDO-DOING-DELAY" },
    query: { className: props.classCode, status: "" }
  },
  {
    icon: "abnormalBg",
    label: "异常任务",
    path: "/all/safeManage/abnormal/apply",
    query_done: { taskType: "myToDoCount" },
    query: { className: props.classCode, taskType: "initiatedByMeCount" }
  },
  {
    icon: "callInWorkOrderBg",
    label: "话务工单任务",
    path: ""
  },
  {
    icon: "otherBg",
    label: "其它任务",
    path: fourSubjectTaskViewPathMap[props.classCode],
    query_done: { taskStatusCode: "UNDO" },
    query: { className: props.classCode, taskTypeCode: "" }
  }
]);
const getCategroyList = async () => {
  categroyList.value = [];
  const data: any = await queryChildByTypeCodeAndItemValue({
    value: "MODULE",
    typeCode: "OPERATION_TASKBOARD"
  });
  if (data && data.length) {
    data.forEach(v => {
      categroyList.value.push({
        name: v.itemName,
        code: v.itemValue
      });
    });
  } else {
    categroyList.value = [];
  }
};
const countData = ref<any>({});
const getTaskCount = async () => {
  try {
    const startTime = dayjs().startOf("day").format("YYYY-MM-DD HH:mm:ss");
    const endTime = dayjs().endOf("day").format("YYYY-MM-DD HH:mm:ss");
    let res = await queryTaskCount({
      startTime,
      endTime,
      clazzCode: props.classCode
    });
    let totalNum = 0;
    let undoNum = 0;
    let doneNum = 0;
    if (res && res.length) {
      categroyList.value.forEach(v => {
        let target = res.filter(r => r.taskModuleName == v.code);
        if (target && target.length) {
          v.undoTasks = target[0].undoTasks;
          v.doneTasks = target[0].doneTasks;
          v.totalTasks = target[0].totalTasks;
          totalNum += v.totalTasks;
          undoNum += v.undoTasks;
          doneNum += v.doneTasks;
        }
      });
    }
    countData.value = {
      totalNum,
      undoNum,
      doneNum
    };
  } catch (error) {}
};
const init = async () => {
  await getCategroyList();
  await getTaskCount();

  for (let i = 0; i < tempList.value.length; i++) {
    const mergeCategroy = categroyList.value.find(e => e.name === tempList.value[i].label);
    for (const key in mergeCategroy) {
      const element = mergeCategroy[key];
      tempList.value[i][key] = element;
    }
  }
  tempList.value[tempList.value.length - 1].query.taskTypeCode = tempList.value[tempList.value.length - 1].code;
  await nextTick();
  initChart();
};

// const initLoading = () => {
//   const target = `.${deviceStatisticsTasksClass.value}`;
//   loadingInstance.value = useInitLoading(target);
//   setTimeout(() => {
//     loadingInstance.value.close();
//   }, loadingTimeout);
//   return loadingInstance.value;
// };

const toPage = () => {
  const fourSubjectTaskViewPathMap = {
    GAS: "/gas/operation/taskView",
    MACHINE: "/machine/operation/taskOverView",
    ELECTRICTITY: "/electricity/operation/taskView",
    WATER: "/water/taskView"
  };
  const query: any = { className: props.classCode };

  const path = fourSubjectTaskViewPathMap[props.classCode];

  router.push({ path, query });
};
const chartRef = ref();
const chartOptions = ref<any>(null);

const initChart = async () => {
  const ec = await chartRef.value.getEcharts();
  if (!ec) return null;
  const { getWidth = null } = ec;
  // const labelLayout = function (params) {
  //   if (!getWidth) return null;
  //   const isLeft = params.labelRect.x < getWidth() / 2;
  //   const points = params.labelLinePoints;
  //   points[2][0] = isLeft ? params.labelRect.x : params.labelRect.x + params.labelRect.width;
  //   return { labelLinePoints: points };
  // };
  let total = countData.value?.totalNum || 0;
  let done = countData.value?.doneNum || 0;
  let undo = countData.value?.undoNum || 0;
  chartOptions.value = {
    title: {
      text: "{a|" + total + "}{b|项}",
      left: "center",
      top: "center",
      textStyle: {
        rich: {
          a: {
            fontSize: 18,
            fontWeight: "bold",
            color: props.dark ? "#00C2FF" : "#2885F7"
          },
          b: {
            fontSize: 14,
            color: props.dark ? "#ffffff" : "#363636",
            lineHeight: 20
          }
        }
      }
    },
    tooltip: {
      trigger: "item",
      formatter: function (params) {
        const { marker, name, value, percent } = params;
        const d = `${marker}${name}：  ${value}（${percent}%）`;
        return d;
      }
    },
    grid: {
      left: 0,
      right: 0,
      top: 0,
      bottom: 0,
      containLabel: true
    },
    series: [
      {
        name: "",
        type: "pie",
        radius: ["40%", "60%"],
        center: ["50%", "50%"],
        label: {
          // alignTo: "edge",
          formatter: `{name|{b}}{percent| ( {d}% )}\n{num|{c}项}`,
          // minMargin: 2,
          // edgeDistance: 10,
          lineHeight: 20,
          rich: {
            num: {
              fontSize: 10,
              color: props.dark ? "#fff" : "#000",
              lineHeight: 20,
              fontWeight: 600
            },
            percent: {
              fontSize: 10,
              color: props.dark ? "#fff" : "#000",
              lineHeight: 20
            }
          }
        },

        // labelLayout,
        data: [
          {
            name: "待完成",
            value: undo,
            itemStyle: {
              color: "#FF0844"
            }
          },
          {
            name: "已完成",
            value: done,
            itemStyle: {
              color: "#36CB7A"
            }
          }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)"
          }
        }
      }
    ]
  };
  chartRef.value.forceUpdateEcharts();
};
onMounted(async () => {
  await init();
});
defineExpose({
  init
});
</script>

<template>
  <modelBox :title="title" :borderRadius="false" :dark="dark">
    <px-scrollbar v-if="tempList?.length" :wrap-class="deviceStatisticsTasksClass">
      <div class="device-statistics-tasks">
        <div class="left">
          <echartsChart ref="chartRef" :boxShadow="false" :options="chartOptions" :dark="dark" noBorder noPadding />
        </div>
        <div class="right">
          <div v-for="item in tempList" :key="item.icon" class="right-item">
            <deviceStatisticsTasksItem :data="item" :dark="dark" />
          </div>
        </div>
      </div>
    </px-scrollbar>
    <px-empty v-else :image-size="56" :class="deviceStatisticsTasksClass" />
    <template v-if="arrow" #title>
      <px-button :icon="ArrowRightBold" type="primary" text plain @click="toPage" />
    </template>
  </modelBox>
</template>

<style lang="scss" scoped>
.px-scrollbar {
  width: 100%;
  height: 100%;

  :deep(.px-scrollbar__view) {
    width: 100%;
    height: 100%;

    .device-statistics-tasks {
      display: flex;
      width: 100%;
      height: 100%;

      .left {
        flex: 1;
        height: 100%;
      }

      .right {
        display: flex;
        flex: 0 0 66%;
        flex-wrap: wrap;
        gap: 16px;
        align-items: center;
        justify-content: right;
        height: 100%;

        .right-item {
          box-sizing: border-box;
          display: flex;
          flex: 0 0 23%; /* 每个项目占25%的宽度 */
          flex-direction: column;
          height: 58px;
          font-size: 14px;
          font-weight: 600;
        }
      }
    }
  }
}

.px-button {
  padding-right: 0;
}
</style>
